package crawler.cnki.utils;

import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Component
public class HttpUtils {
    private PoolingHttpClientConnectionManager cm;

    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();
        this.cm.setMaxTotal(100);
        this.cm.setDefaultMaxPerRoute(10);
    }


    public String doGetHtml(HttpGet httpGet, String headerName) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
//        HttpGet httpGet=new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36");
        httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpGet.setConfig(getConfig());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null) {
                    if (headerName!=null&&headerName.equals("EC")) {
                        Header[] allHeaders = response.getAllHeaders();
                        for (Header header : allHeaders) {
                            if (header.getName().equals("Set-Cookie")) {
                                return header.getValue() + EntityUtils.toString(response.getEntity(), "utf8");
                            }
                        }
                    }
                    return EntityUtils.toString(response.getEntity(), "utf8");
                }
            } else if (response.getStatusLine().getStatusCode() == 302) {
                if (response.getEntity() != null) {
                    Header[] allHeaders = response.getAllHeaders();
                    for (Header header : allHeaders) {
                        if (header.getName().equals(headerName)) {
                            return header.getValue();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public String doGetImage(String url) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36");
        httpGet.setConfig(getConfig());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null) {
                    String extName = url.substring(url.lastIndexOf("."));

                    String picName = UUID.randomUUID().toString() + extName;

                    OutputStream outputStream = new FileOutputStream(new File("D:\\学习\\大三上\\learning\\crawler-jd\\images\\" + picName));
                    response.getEntity().writeTo(outputStream);

                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public String doPostHtml(HttpPost httpPost, String headerName) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
//        HttpGet httpGet=new HttpGet(url);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setConfig(getConfig());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null) {
                    return EntityUtils.toString(response.getEntity(), "utf8");
                }
            } else if (response.getStatusLine().getStatusCode() == 302) {
                if (response.getEntity() != null) {
                    Header[] allHeaders = response.getAllHeaders();
                    for (Header header : allHeaders) {
                        if (header.getName().equals(headerName)) {
                            return header.getValue();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    private RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(500)
                .setSocketTimeout(10000)
                .setRedirectsEnabled(false)
                .build();
        return config;
    }
}
